package org.example.userservice.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.example.context.BaseContext;
import org.example.mapper.AddressMapper;
import org.example.mapper.CartMapper;
import org.example.mapper.OrderMapper;
import org.example.mapper.SalelogMapper;
import org.example.pojo.PageBean;
import org.example.pojo.entity.*;
import org.example.pojo.userdto.OrderCheckDTO;
import org.example.userservice.ShoppingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
@Slf4j
public class ShoppingServiceImpl implements ShoppingService {

    @Autowired
    private SalelogMapper salelogMapper;
    @Autowired
    private AddressMapper addressMapper;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private CartMapper cartMapper;
    @Override
    public boolean order(int addressid) {
        Order order = new Order();
        order.setUserid(BaseContext.getCurrentId());
        order.setAddressid(addressid);
        AddressBook addressBook = addressMapper.findById(addressid);
        if(addressBook.getUserid()!=order.getUserid()){
            return false;
        }
        String address = addressBook.toString();

        log.info(addressBook.getConsignee().toString());
        Cart cart = new Cart();
        cart.setUserid(BaseContext.getCurrentId());
        List<Cart>  cartList= cartMapper.list(cart);
        for (Cart cart1 : cartList) {
            order.setUsername(cart1.getUsername());
            order.setGoodid(cart1.getGoodid());
            order.setPrice(cart1.getPrice());
            order.setGoodname(cart1.getGoodname());
            order.setNum(cart1.getNum());
            order.setState(2);
            order.setAddress(address);
            order.setConsignee(addressBook.getConsignee().toString());
            order.setSaletime(LocalDateTime.now());
            orderMapper.insertOrder(order);
        }
        cartMapper.deletebyid(BaseContext.getCurrentId());
        return true;
    }

    @Override
    public void pay(Order order) {
        orderMapper.buyOrder(order);
        SaleLog saleLog = new SaleLog();
        saleLog.copyorder(order);
        saleLog.setState(1);
        salelogMapper.insertSaleLog(saleLog);
    }

    @Override
    public PageBean getOrder(OrderCheckDTO orderCheckDTO) {
        Order order = new Order();
        order.setUserid(BaseContext.getCurrentId());
        order.setState(orderCheckDTO.getState());
        Integer page=orderCheckDTO.getPage(),pageSize=orderCheckDTO.getPageSize();
        PageHelper.startPage(page, pageSize);
        List<Order> list = orderMapper.list(order);
        Page<Order> orderPage = (Page<Order>) list;
        PageBean p = new PageBean(orderPage.getTotal(),orderPage.getResult());
        return p;
    }
}
